package nut.system;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.Doc;
import com.sun.javadoc.SeeTag;
import com.sun.javadoc.Tag;
/**
 * Core item for nut
 * 
 * @category alpha
 * @author Mark Farnsworth
 */
class NutItem {
	final List<NutAuthor> authors = new ArrayList<NutAuthor>();
	final List<NutVersion> bags = new ArrayList<NutVersion>();
	List<NutCategory> categories = new ArrayList<NutCategory>();
	DateFormat dateFormat = NutFactory.the.dateFormat;
	Doc doc;
	final Integer id;
	final String name;
	final List<NutItem> nuts = new ArrayList<NutItem>();
	protected NutFactory system = NutFactory.the;
	NutItem(final String name) {
		id = NutFactory.the.nextId();
		this.name = name;
	}
	void bag(final NutVersion bag) {
		bag.nuts.add(this);
		bags.add(bag);
	}
	void doc(final Doc method) {
		doc = method;
		for (final Tag item : method.tags())
			if (item instanceof SeeTag)
				onSeeTag(item);
			else if ("@author".equals(item.name()))
				onAuthorTag(item);
			else if ("@version".equals(item.name()))
				onVersionTag(item);
			else if ("@category".equals(item.name()))
				onCategoryTag(item);
	}
	private void onAuthorTag(final Tag item) {
		authors.add(system.farmer(item.text().trim()));
	}
	private void onCategoryTag(final Tag item) {
		categories.add(NutFactory.the.category(item.text().trim()));
	}
	private void onSeeTag(final Tag item) {
		final SeeTag s = (SeeTag) item;
		final ClassDoc r = s.referencedClass();
		if (r != null) {
			final String name = r.qualifiedTypeName();
			System.out.println(name);
			nuts.add(NutFactory.the.nut(name));
		}
	}
	private void onVersionTag(final Tag item) {
		final String[] s = item.text().trim().split(",");
		int i = 0;
		final String version = s.length > i ? s[i++] : null;
		final NutVersion bag = system.bag(version);
		if (s.length > i) {
			final Date date = parseDate(s[i++]);
			bag.target.put(date, date);
		}
		bags.add(bag);
	}
	private Date parseDate(final String dateString) {
		Date date;
		try {
			date = dateFormat.parse(dateString);
		} catch (final ParseException e) {
			throw new RuntimeException(e);
		}
		return date;
	}
}
